<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\controller\Token;
use app\controller\AesUtil;
use app\controller\Acc;
use think\facade\Cache;

class Wxmt{
    /*
    *支付请求
    *客户端发起支付请求，上传支付金额挤微信个人"code"
    *调用微信个人信息接口，获得openid.
    */
    public function get_openid(){
        $all = Request::param();
        if(empty($all['code'])){
            return json(['code'=>0,'msg'=>'Invalid parameter [code] or [money].']);
        }

        $appid = 'wx15d32cb44449c60f';
        $secret = "34d1ab0202953f1d537e7a147d12dcea";
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        $url = sprintf($url,$appid,$secret,$all['code']);
        $str = file_get_contents($url);
        $json = json_decode($str);
        $arr = get_object_vars($json);

        if(empty($arr['openid']) || empty($arr['session_key'])){
            return json(['code'=>0,'msg'=>'Error of openid get.']);
        }
        
        return json(['code'=>1,'openid'=>$arr['openid']]);

        //return json($this->wx_pay($arr['openid'],$all['money']));
    }


    //转账，提现
    public function money_transfer(){
        $last_tx_time=Cache::get('last_tx_time');
        if(!empty($last_tx_time)){
            $timedif= time()-$last_tx_time;
            if($timedif<5) {
                Cache::set('last_tx_time',time());
                return json(['message'=>'请不要连续点击！'.$timedif]);
            }
        }
        Cache::set('last_tx_time',time()); //记录提现时间

        $params=Request::param();
        if(empty($params['money']) || !is_numeric($params['money'])) return json(['message'=>'金额错误！']);

        $token = new Token();
        $arr = $token->check_token($params['token']); 
        if($arr['code']<1){
            return json(['message'=>$arr['msg']]);
        }
        $customer=$arr['customer'];
        if(!$customer['fee_time']) return json(['message'=>'温馨提示：本次红包活动，只有学员才可以提现哦！']);

        if($params['money']>200) return json(['message'=>'单次提现不能超过200元哦！']);
        //if($params['money']<20) return json(['message'=>'20元以上才能提现哦！']);

        $post_data = [
            "appid" => 'wx15d32cb44449c60f',//appid
            "out_batch_no" => 'PATX'.date('YmdHis').mt_rand(100000, 999900),//商家批次单号
            "batch_name" => '提现',//批次名称
            "batch_remark" => '提现',//批次备注
            "total_amount" => intval(strval($params['money'] * 100)),// 转账金额单位为“分”
            "total_num" => 1, // 转账总笔数
            //此处可以多笔提现  组合二维数组放到transfer_detail_list即可   我这里单笔操作，写死了
            "transfer_detail_list" => [
                [
                    'out_detail_no' => 'wlss'.date('YmdHis').mt_rand(100000, 999900),
                    'transfer_amount' => intval(strval($params['money'] * 100)),
                    'transfer_remark' => '提现到账',
                    'openid' => $params['openid'],
                ]
             ]
        ];    
                    
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $result = self::wx_post($url, json_encode($post_data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        $result2 = json_decode($result,true);
        
        Cache::set('get_money',$result2);

        if(!empty($result2['out_batch_no'])){
            $res = $this->acc_log($customer,$params['money']);
        }

        return json($result);
    }
 
 
    public function check_log(){
        $all = Request::param();
        if(!empty($all['get_money'])){
            $aa = Cache::get('get_money');
            return var_dump($all,$aa);
        }
    }
 
    //提交post
    public static function wx_post($url, $param)    {
        $authorization = self::getV3Sign($url,"POST",$param);
        $curl = curl_init();
        $headers = [
            'Authorization:' . $authorization,
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_POST, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    
        
    public static function getV3Sign($url, $http_method, $body){
        $merchantId = '1649063218'; // 商户号 
        $merchantSerialNumber = '490DAA2C83213DA598A84A56F391076286EC0CF8'; // 商户API证书序列号         
        $nonce = strtoupper(self::createNonceStr());
        $timestamp = time();
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $cert_dir = 'attach/cert/'; //绝对路径
        $sslKeyPath = $cert_dir."apiclient_key.pem";
        //拼接参数
        $message = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        $private_key = self::getPrivateKey($sslKeyPath);
        openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption');
        $sign   = base64_encode($raw_sign);
        $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%s",serial_no="%s",signature="%s"',$merchantId,$nonce,$timestamp,$merchantSerialNumber,$sign);
        return $token;
    }
 
 
    //生成随机16个字符的字符串
    public static function createNonceStr($length = 16){ 
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
 
 
    public static function getPrivateKey($filepath = ''){
        if (empty($filepath)) {
            //私钥位置
            $cert_dir = 'attach/cert/';
            $filepath = $cert_dir."apiclient_key.pem";
        }
        return openssl_get_privatekey(file_get_contents($filepath));
    }

    //提现成功，记一条账单，并扣相应余额
    public function acc_log($customer,$money,$memo='提现'){
        $acc_log=array(
            'type'=>7,
            'customer_id'=>$customer['id'],
            'dept_id'=>$customer['dept_id'],
            'money'=>-abs($money),
            'memo'=>$memo,
            'payment'=>'wx',
            'creater'=>2,
            'create_time'=>date('Y-m-d H:i:s'),
            'status'=>2
        );
        Db::table('acc_log')->insert($acc_log);
        $customer['money']-=$money;
        $customer['money_v'] = md5($customer['create_time'].$customer['money']);

        Db::table('customer')->update($customer);
    }

}
 